import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InventoryApi } from '#/models/inventory/inventory';

import { z } from '#/adapter/form';
import { requestClient } from '#/api/request';
import { $t } from '#/locales';
import { op } from '#/utils/permission';

/**
 * 获取编辑表单的字段配置
 * 根据inventory_check表定义，确保所有字段配置与后端模型一致
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      fieldName: 'warehouse_id',
      label: $t('inventory.warehouse.name'),
      rules: z
        .number()
        .min(1, $t('ui.formRules.required', [$t('inventory.warehouse.name')])),
      componentProps: {
        allowClear: false,
        placeholder: $t('common.selectPlaceholder', [
          $t('inventory.warehouse.name'),
        ]),
        api: () => requestClient.get('/inventory/warehouse/'),
        resultField: 'results', // Django REST framework默认的分页数据字段
        labelField: 'warehouse_name',
        valueField: 'warehouse_id',
        class: 'w-full',
      },
    },
    {
      component: 'Input',
      fieldName: 'check_code',
      label: $t('inventory.check.code'),
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', [$t('inventory.check.code')]))
        .max(
          50,
          $t('ui.formRules.maxLength', [$t('inventory.check.code'), 50]),
        ),
      componentProps: {
        placeholder: $t('common.inputPlaceholder', [
          $t('inventory.check.code'),
        ]),
        maxlength: 50,
        showCount: true,
        class: 'w-full',
      },
    },
    {
      component: 'Textarea',
      fieldName: 'remark',
      label: $t('system.remark'),
      rules: z
        .string()
        .max(200, $t('ui.formRules.maxLength', [$t('system.remark'), 200])),
      componentProps: {
        placeholder: $t('common.inputPlaceholder', [$t('system.remark')]),
        rows: 3,
        maxLength: 200,
        showCount: true,
        class: 'w-full',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'check_date',
      label: $t('inventory.check.date'),
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', [$t('inventory.check.date')])),
      componentProps: {
        placeholder: $t('common.selectPlaceholder', [
          $t('inventory.check.date'),
        ]),
        format: 'YYYY-MM-DD',
        class: 'w-full',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'checker_id',
      label: $t('inventory.check.checker'),
      rules: z
        .number()
        .min(1, $t('ui.formRules.required', [$t('inventory.check.checker')])),
      componentProps: {
        placeholder: $t('common.inputPlaceholder', [
          $t('inventory.check.checker'),
        ]),
        min: 1,
        class: 'w-full',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'approver_id',
      label: $t('inventory.check.approver'),
      rules: z.number().optional(),
      componentProps: {
        placeholder: $t('common.inputPlaceholder', [
          $t('inventory.check.approver'),
        ]),
        min: 1,
        class: 'w-full',
      },
    },
    {
      component: 'Select',
      fieldName: 'check_type',
      label: $t('inventory.check.type'),
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', [$t('inventory.check.type')])),
      componentProps: {
        placeholder: $t('common.selectPlaceholder', [
          $t('inventory.check.type'),
        ]),
        options: [
          { label: $t('inventory.check.type.full'), value: 'full' },
          { label: $t('inventory.check.type.partial'), value: 'partial' },
        ],
        class: 'w-full',
      },
      defaultValue: 'full',
    },
  ];
}

/**
 * 获取搜索表单的字段配置
 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'check_code',
      label: $t('inventory.check.code'),
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: $t('inventory.check.status'),
      componentProps: {
        allowClear: true,
        options: [
          { label: $t('inventory.check.status.draft'), value: 'draft' },
          {
            label: $t('inventory.check.status.inProgress'),
            value: 'in_progress',
          },
          { label: $t('inventory.check.status.completed'), value: 'completed' },
          { label: $t('inventory.check.status.closed'), value: 'closed' },
        ],
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'warehouse_id',
      label: $t('inventory.warehouse.name'),
      componentProps: {
        allowClear: true,
        api: () => requestClient.get('/inventory/warehouse/'),
        resultField: 'results',
        labelField: 'warehouse_name',
        valueField: 'warehouse_id',
      },
    },
    {
      component: 'Input',
      fieldName: 'checker_id',
      label: $t('inventory.check.checker'),
    },
    {
      component: 'RangePicker',
      fieldName: 'date_range',
      label: $t('common.dateRange'),
    },
  ];
}

/**
 * 获取表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<InventoryApi.InventoryCheck>,
): VxeTableGridOptions<InventoryApi.InventoryCheck>['columns'] {
  // 状态映射表
  const statusMap: Record<string, string> = {
    draft: $t('inventory.check.status.draft'),
    in_progress: $t('inventory.check.status.inProgress'),
    completed: $t('inventory.check.status.completed'),
    closed: $t('inventory.check.status.closed'),
  };

  // 状态颜色映射表
  const colorMap: Record<string, string> = {
    draft: '#d9d9d9',
    in_progress: '#1890ff',
    completed: '#52c41a',
    closed: '#bfbfbf',
  };

  return [
    {
      title: '序',
      type: 'seq',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'check_code',
      title: $t('inventory.check.code'),
      width: 180,
    },
    {
      cellRender: {
        name: 'CellTag',
      },
      field: 'status',
      title: $t('inventory.check.status'),
      width: 100,
      formatter: ({ row }) => {
        const status = statusMap[row.status || ''] || '-';
        const color = colorMap[row.status || ''] || '#d9d9d9';
        return `<span style="color: ${color};">${status}</span>`;
      },
    },
    {
      field: 'warehouse',
      title: $t('inventory.warehouse.name'),
      width: 150,
      formatter: ({ row }) => {
        return row.warehouse?.warehouse_name || '-';
      },
    },
    {
      field: 'details',
      title: $t('inventory.check.detailCount'),
      width: 120,
      formatter: ({ row }) => {
        return row.details?.length || 0;
      },
    },
    {
      field: 'checker_id',
      title: $t('inventory.check.checker'),
      width: 100,
    },
    {
      field: 'check_date',
      title: $t('inventory.check.date'),
      width: 120,
      formatter: ({ row }) => {
        return row.check_date || '-';
      },
    },
    {
      field: 'create_time',
      title: $t('system.createTime'),
      width: 180,
      formatter: ({ row }) => {
        return row.create_time
          ? new Date(row.create_time).toLocaleString('zh-CN')
          : '-';
      },
    },
    {
      field: 'update_time',
      title: $t('system.updateTime'),
      width: 180,
      formatter: ({ row }) => {
        return row.update_time
          ? new Date(row.update_time).toLocaleString('zh-CN')
          : '-';
      },
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'name',
          nameTitle: $t('inventory.check.name'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('inventory:check:detail', 'detail'),
          op('inventory:check:edit', 'edit'),
          op('inventory:check:start', 'start'),
          op('inventory:check:complete', 'complete'),
          op('inventory:check:close', 'close'),
          op('inventory:check:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 180,
    },
  ];
}
